package com.ccf.business.etl.websocket.filter;

import com.common.model.pojo.UserInfo;
import com.service.websocket.to.User;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 描述：
 * 用户信息过滤
 * @author xianggj
 * @Date 2021/9/15 15:37
 **/
@Component
@Lazy
public class UserInfoFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        String connection = request.getHeader(HttpHeaders.CONNECTION);
        if (HttpHeaders.UPGRADE.equalsIgnoreCase(connection)){
            try {
                UserInfo defaultUser = UserInfo.getDefaultUser();
                session.setAttribute(User.USER_KEY, new User(defaultUser.getUserId(),
                                defaultUser.getUserName()));
            } catch (Exception e) {
                //获取用户失败
                e.printStackTrace();
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
